package com.slipper.system.ai.controller;

import com.slipper.ai.vector.KnowledgeVectorService;
import com.slipper.core.gson.GsonUtil;
import com.slipper.system.ai.bo.KnowledgeEmbeddingBO;
import com.slipper.system.ai.bo.KnowledgeFileBO;
import com.slipper.system.ai.service.KnowledgeEmbeddingService;
import com.slipper.system.ai.service.KnowledgeFileService;
import com.slipper.system.ai.vo.KnowledgeVO;
import com.slipper.util.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import org.springframework.ai.document.Document;
import com.slipper.system.ai.bo.KnowledgeBO;
import com.slipper.system.ai.service.KnowledgeService;
import com.slipper.constants.Constants;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/system/knowledge")
public class KnowledgeController {
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KnowledgeFileService knowledgeFileService;
    @Resource
    private KnowledgeEmbeddingService knowledgeEmbeddingService;
    @Resource
    private KnowledgeVectorService knowledgeVectorService;
    
    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody KnowledgeBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(knowledgeService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody KnowledgeBO bo) {
        return ResultUtil.successResult(knowledgeService.queryList(bo));
    }
    
    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody KnowledgeBO bo) {
        return ResultUtil.successResult(knowledgeService.queryPage(bo));
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody KnowledgeBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(knowledgeService.save(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody KnowledgeBO bo) {
        return ResultUtil.deleteResult(knowledgeService.delete(bo));
    }

    @PostMapping(value = "/hitTest")
    public String hitTest(@RequestBody KnowledgeBO bo) {
        List<Document> documentList = knowledgeVectorService.similaritySearch(
                bo.getId(),
                bo.getQuery(),
                bo.getTopSize(),
                bo.getSimilarityThreshold() == null ? null : bo.getSimilarityThreshold().doubleValue());
        StringBuilder similarityText = new StringBuilder();
        if (documentList != null && !documentList.isEmpty()) {
            for (int i = 0; i < documentList.size(); i++) {
                similarityText.append("\n第")
                        .append(i + 1)
                        .append("条、---------------------------------------")
                        .append("\n")
                        .append(documentList.get(i).getText())
                        .append("\n");
            }
        }
        return ResultUtil.successResult("获取成功。", similarityText.toString());
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody KnowledgeBO bo) {
        KnowledgeVO vo = new KnowledgeVO();
        vo.setKnowledgeList(knowledgeService.queryList(bo));
        vo.getKnowledgeList().forEach(knowledgeBO -> {
            KnowledgeFileBO knowledgeFileBO = new KnowledgeFileBO();
            knowledgeFileBO.setKnowledgeId(knowledgeBO.getId());
            List<KnowledgeFileBO> knowledgeFileList = knowledgeFileService.queryList(knowledgeFileBO);
            knowledgeFileList.forEach(knowledgeFile -> {
                try {
                    knowledgeFile.setBase64(AffixUtil.readFileToBase64(knowledgeFile.getFileId()));
                } catch (Exception e) {
                    throw new RuntimeException("文档读取出错！", e);
                }
            });
            vo.addKnowledgeFile(knowledgeFileList);

            KnowledgeEmbeddingBO knowledgeEmbeddingBO = new KnowledgeEmbeddingBO();
            knowledgeEmbeddingBO.setKnowledgeId(knowledgeBO.getId());
            vo.addKnowledgeEmbedding(knowledgeEmbeddingService.queryList(knowledgeEmbeddingBO));
        });
        String fileName = "knowledge-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(KnowledgeBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }
        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            KnowledgeVO vo = GsonUtil.fromJson(AESUtil.decrypt(content), KnowledgeVO.class);
            knowledgeService.saveList(vo.getKnowledgeList());
            knowledgeFileService.saveList(vo.getKnowledgeFileList());
            knowledgeEmbeddingService.saveList(vo.getKnowledgeEmbeddingList());
            return ResultUtil.successResult("导入供应商模型成功。");
        } catch (Exception e) {
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
